package org.jumiz.javafx.client.pages.commonents;

import com.alibaba.fastjson2.JSON;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.control.*;
import javafx.scene.layout.Background;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.HBox;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 一行一个元素的表单
 */
public class JumizForm1 extends GridPane {

    private int rowIndex = 0;

    private GridPane innerPane = new GridPane();

    private HashMap<String, TextInputControl> fieldMap = new LinkedHashMap<>();

    public JumizForm1() {
        super();
        super.setAlignment(Pos.CENTER);
//        super.setHgap(10);
//        super.setVgap(10);
//        super.setPadding(new Insets(25, 25, 25, 25));
//        super.setStyle("-fx-background-color: white;");

//        innerPane.setAlignment(Pos.CENTER);
        innerPane.setHgap(10);
        innerPane.setVgap(10);
        innerPane.setPadding(new Insets(25, 25, 25, 25));
        innerPane.setStyle("-fx-background-color: white;");
        this.add(innerPane, 0, 0);
    }

    public synchronized JumizForm1 addTextField(String labelName) {
        int rowIndex = this.getRowIndexAndInc();
        innerPane.add(new Label(labelName + "："), 0, rowIndex);
        TextField textField = new TextField();
        textField.setPromptText("请输入" + labelName);
        innerPane.add(textField, 1, rowIndex);
        fieldMap.put(labelName, textField);
        return this;
    }

    public synchronized JumizForm1 addSubmitButton(String buttonName, EventHandler<ActionEvent> value) {
        Button submitButton = new Button(buttonName);
        submitButton.getStyleClass().addAll("btn", "btn-primary");
        submitButton.setOnAction(value);

        HBox hBox = new HBox(10);
        hBox.setAlignment(Pos.BOTTOM_RIGHT);
        hBox.getChildren().add(submitButton);
        innerPane.add(hBox, 1, this.getRowIndexAndInc());
        return this;
    }

    public int getRowIndex() {
        return rowIndex;
    }

    public int getRowIndexAndInc() {
        int temp = rowIndex;
        rowIndex++;
        return temp;
    }

    public Map<String, String> getFormData() {
        Map<String, String> collect = fieldMap.entrySet().stream().collect(Collectors.toMap(item -> item.getKey(), item -> item.getValue().getText()));
        return collect;
    }
}
